<template>
	<view class="user-list-container">
		<view class="search-bar">
			<input type="text" v-model="searchKey" placeholder="请输入用户名搜索" />
			<button @click="searchUser">搜索</button>
		</view>

		<view class="user-table">
			<view class="table-header">
				<view class="table-cell">姓名</view>
				<view class="table-cell">手机号</view>
				<view class="table-cell">性别</view>
				<view class="table-cell">家庭地址</view>
				<view class="table-cell">角色</view>
				<view class="table-cell">密码</view>
				<view class="table-cell">删除</view>
			</view>

			<view class="table-body">
				<view class="table-row" v-for="(user, index) in userList" :key="index">
					<view class="table-cell">{{ user.name }}</view>
					<view class="table-cell">{{ user.phone }}</view>
					<view class="table-cell">{{ user.gender === '1' ? '男' : user.gender === '2' ? '女' : '未知' }}</view>
					<view class="table-cell">{{ user.address || '无' }}</view>
					<view class="table-cell">{{ getUserRoleText(user.role) }}</view>
					<view class="table-cell">
						<button class="password-btn" @click="showModifyPassword(user.name)">修改密码</button>
					</view>
					<view class="table-cell">
						<button class="del-btn" @click="delUser(user.id)">删除</button>
					</view>
				</view>
			</view>
		</view>

		<view class="pagination">
			<button :disabled="currentPage === 1" @click="prevPage">上一页</button>
			<text>{{ currentPage }}/{{ totalPages }}</text>
			<button :disabled="currentPage === totalPages" @click="nextPage">下一页</button>
		</view>
		 <!-- 引入修改密码组件 -->
		<ModifyPassword ref="modifyPassword" />
	</view>
</template>

<script>
	import request from '@/utils/request.js';
	// 导入组件
	import ModifyPassword from '@/components/ModifyPassword.vue';

	export default {
		components: {
		    ModifyPassword
		  },
		data() {
			return {
				userList: [],
				searchKey: '',
				currentPage: 1,
				pageSize: 10,
				totalPages: 1
			}
		},
		// 创建期
		beforeCreate() {
			console.log('组件：beforeCreate')
		},
		created() {
			console.log('组件：created')
			// 初始化数据请求
			this.getUserList()
		},
		activated(){
			console.log("activated 被调用")
			this.getUserList()
		},
		methods: {
			async getUserList() {
				try {
					const res = await request.get('/api/users/allUser', {
						params: {
							username: this.searchKey,
							currentPage: this.currentPage,
							pageSize: this.pageSize
						}
					});
					console.log("key:" + this.searchKey + ", pageNo: " + this.currentPage + ", pageSize:" + this.pageSize)
					console.log("=======result:" + res)
					this.userList = res.content || [];
					this.totalPages = res.page.totalPages;
					// if (res.code === 200) {
					// 	this.userList = res.data.list || [];
					// 	this.totalPages = Math.ceil(res.data.total / this.pageSize);
					// } else {
					// 	uni.showToast({
					// 		title: res.message || '获取用户列表失败',
					// 		icon: 'none'
					// 	});
					// }
				} catch (error) {
					console.error('获取用户列表错误:', error);
					uni.showToast({
						title: '网络错误，请稍后重试',
						icon: 'none'
					});
				}
			},
		   //点击修改密码时调用组件方法
			showModifyPassword(username) {
			  this.$refs.modifyPassword.showModifyDialog(username);
			},
			getUserRoleText(role) {
				switch (role) {
					case 'ROLE_ADMIN':
						return '管理员';
					case 'ROLE_TEACHER':
						return '老师';
					case 'ROLE_USER':
						return '学生';
					default:
						return '未知';
				}
			},

			delUser(userId) {
				uni.navigateTo({
					url: `/pages/dashboard/user/editUser?userId=${userId}`
				});
			},

			changePassword(userId) {
				uni.showModal({
					title: '修改密码',
					content: '请输入新密码',
					editable: true,
					confirmText: '确认修改',
					success: async (res) => {
						if (res.confirm) {
							try {
								const result = await request.post(`/api/user/changePassword/${userId}`, {
									password: res.content
								});

								if (result.code === 200) {
									uni.showToast({
										title: '密码修改成功',
										icon: 'success'
									});
								} else {
									uni.showToast({
										title: result.message || '密码修改失败',
										icon: 'none'
									});
								}
							} catch (error) {
								console.error('修改密码错误:', error);
								uni.showToast({
									title: '网络错误，请稍后重试',
									icon: 'none'
								});
							}
						}
					}
				});
			},

			searchUser() {
				this.currentPage = 1;
				this.getUserList();
			},

			prevPage() {
				if (this.currentPage > 1) {
					this.currentPage--;
					this.getUserList();
				}
			},

			nextPage() {
				if (this.currentPage < this.totalPages) {
					this.currentPage++;
					this.getUserList();
				}
			}
		}
	}
</script>

<style>
	.user-list-container {
		padding: 15px;
	}

	.search-bar {
		display: flex;
		margin-bottom: 20px;
	}

	.search-bar input {
		flex: 1;
		padding: 8px;
		border: 1px solid #dcdfe6;
		border-radius: 4px;
		margin-right: 10px;
	}

	.search-bar button {
		padding: 8px 16px;
		background-color: #409eff;
		color: white;
		border: none;
		border-radius: 4px;
	}

	.user-table {
		border: 1px solid #ebeef5;
		border-radius: 4px;
		overflow: hidden;
	}

	.table-header {
		display: flex;
		background-color: #f5f7fa;
		font-weight: bold;
	}

	.table-row {
		display: flex;
		border-top: 1px solid #ebeef5;
	}

	.table-row:nth-child(even) {
		background-color: #fafafa;
	}

	.table-cell {
		flex: 1;
		padding: 12px;
		text-align: center;
		word-break: break-all;
	}

	.del-btn {
		background-color: #e46468;
		color: white;
		border: none;
		padding: 5px 10px;
		border-radius: 4px;
		margin-right: 5px;
	}

	.password-btn {
		background-color: #67c23a;
		color: white;
		border: none;
		padding: 5px 10px;
		border-radius: 4px;
	}

	.pagination {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-top: 20px;
	}

	.pagination button {
		padding: 8px 16px;
		margin: 0 10px;
		background-color: #409eff;
		color: white;
		border: none;
		border-radius: 4px;
	}

	.pagination button:disabled {
		background-color: #c0c4cc;
		cursor: not-allowed;
	}
</style>